package problem18;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//18.四数之和
// https://leetcode.cn/problems/4sum/

class Solution {
    public List<List<Integer>> fourSum(int[] nums, long target) {
        int n = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i<n-3; ) {
            for(int j = i+1; j<n-2; ) {
                long tar = target - nums[i] - nums[j];
                int l = j+1, r = n-1;
                while(l < r) {
                    if(nums[l] + nums[r] < tar) {
                        l++;
                    }else if(nums[l] + nums[r] > tar) {
                        r--;
                    }else {
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[l]);
                        list.add(nums[r]);
                        ret.add(list);
                        l++;
                        r--;
                        while(l < n && nums[l] == nums[l-1]) l++;
                        while(r > 0 && nums[r] == nums[r+1]) r--;
                    }
                }
                j++;
                while(j < n && nums[j] == nums[j-1]) {
                    j++;
                }
            }
            i++;
            while(i < n && nums[i] == nums[i-1]) {
                i++;
            }
        }
        return ret;
    }
}

/*
a + b + c + d = target
c + d = target-a-b
*/